package org.gitee.weapp.controller;

import com.github.pagehelper.PageHelper;
import org.apache.http.HttpStatus;
import org.gitee.weapp.domain.AjaxResult;
import org.gitee.weapp.domain.entity.Goods;
import org.gitee.weapp.domain.vo.GoodsVo;
import org.gitee.weapp.mapper.GoodsMapper;
import org.gitee.weapp.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsService goodsService;

    @Value("${server.remote-address}")
    private String host;

    @Value("${server.port}")
    private Integer port;

    @GetMapping("/category")
    public AjaxResult getAllCategory() {
        try {
            return AjaxResult.success(goodsMapper.getAllGoodsCategory());
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/list")
    public AjaxResult getGoods(@RequestParam("categoryId") Integer categoryId, Integer pageNum, Integer pageSize) {
        if (null == pageNum) {
            pageNum = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        if (pageNum < 0 || pageSize < 0) {
            return AjaxResult.error(HttpStatus.SC_BAD_REQUEST, "分页不能小于0");
        }

        try {
            PageHelper.startPage(pageNum, pageSize);
            List<Goods> goodsList = goodsMapper.getGoodsByCategoryId(categoryId);
            List<GoodsVo> goodsVoList = goodsList.stream().map(goods -> {
                GoodsVo goodsVo = new GoodsVo(goods);
                goodsVo.setPicUrl("http://" + host + ':' + port + "/goods/pic?goodsId=" + goods.getId());
                return goodsVo;
            }).collect(Collectors.toList());
            return AjaxResult.success(goodsVoList);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/pic")
    public void getGoodsPic(@RequestParam("goodsId") Integer goodsId, HttpServletResponse response) {
        goodsService.getGoodsPic(goodsId, response);
    }
}
